﻿/* Source from Ofir Shemesh
 * http://shemesh.wordpress.com/2008/12/03/silverlight-gridsplitter-with-a-collapse-button-v2/ */

using System;
using System.Windows;
using System.Windows.Controls;

namespace DanielVaughan.Calcium.Gui.Controls
{
	[TemplatePart(Name = ExpandableGridSplitter.VerticalCollapseButtonElement, Type = typeof(Button))]
	[TemplatePart(Name = ExpandableGridSplitter.HorizontalCollapseButtonElement, Type = typeof(Button))]
	public class ExpandableGridSplitter : GridSplitter
	{
		const string VerticalCollapseButtonElement = "VerticalCollapseButton";
		const string HorizontalCollapseButtonElement = "HorizontalCollapseButton";

		protected Button VerticalCollapseButton;
		protected Button HorizontalCollapseButton;

		public ExpandableGridSplitter()
		{
			DefaultStyleKey = typeof(ExpandableGridSplitter);
		}

		#region CollapseButtonString

		public static readonly DependencyProperty CollapseButtonStringProperty = DependencyProperty.Register(
			"CollapseButtonString", typeof(string), typeof(ExpandableGridSplitter), null);

		public string CollapseButtonString
		{
			get
			{
				return (string)GetValue(CollapseButtonStringProperty);
			}
			set
			{
				SetValue(CollapseButtonStringProperty, value);
				if (VerticalCollapseButton != null)
				{
					VerticalCollapseButton.Content = value;
				}
				if (HorizontalCollapseButton != null)
				{
					HorizontalCollapseButton.Content = value;
				}
			}
		}

		#endregion

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();

			VerticalCollapseButton = GetTemplateChild(VerticalCollapseButtonElement) as Button;
			if (VerticalCollapseButton != null)
			{
				VerticalCollapseButton.Click += OnCollapseButtonClickEvent;
			}

			HorizontalCollapseButton = GetTemplateChild(HorizontalCollapseButtonElement) as Button;
			if (HorizontalCollapseButton != null)
			{
				HorizontalCollapseButton.Click += OnCollapseButtonClickEvent;
			}
		}

		protected override Size MeasureOverride(Size availableSize)
		{
			if (VerticalCollapseButton != null)
			{
				VerticalCollapseButton.Width = availableSize.Width - 2;
			}
			if (HorizontalCollapseButton != null)
			{
				HorizontalCollapseButton.Height = availableSize.Height - 2;
			}
			return base.MeasureOverride(availableSize);
		}

		public delegate void CollapseButtonClickEventHandler(object sender);

		public event CollapseButtonClickEventHandler CollapseButtonClickEvent;

		void OnCollapseButtonClickEvent(object sender, RoutedEventArgs e)
		{
			if (CollapseButtonClickEvent != null)
			{
				CollapseButtonClickEvent(sender);
			}
		}

	}
}